package com.findmeastore.bc.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.findmeastore.bc.IBrandBc;
import com.findmeastore.bo.BrandBo;
import com.findmeastore.bo.CategoryBo;
import com.findmeastore.bo.ProductBo;
import com.findmeastore.dao.IBrandDAO;
import com.findmeastore.dao.IProductDAO;
import com.findmeastore.dto.BrandDto;

public class BrandBcImpl implements IBrandBc{
	private IBrandDAO brandDAO;
	private IProductDAO productDao;
	
	public Integer getTotalBrandCount(){
		return brandDAO.getTotalBrandCount();
	}
	
	public List<BrandBo> getAllBrands(){
		return brandDAO.getAllBrands();
	}
	
	public BrandBo getBrandById(Integer id){
		return brandDAO.getBrandById(id);
	}
	
	public void saveBrand(BrandDto dto){
		Integer id = dto.getId();
		BrandBo brandBo = null;
		if(id!=null&&id>0){//update
			brandBo = brandDAO.getBrandById(id);
		}else {//save
			brandBo = new BrandBo();
			brandBo.setCreationTstamp(new Timestamp(System.currentTimeMillis()));
			brandBo.setCreatedByUserId(dto.getModifiedById());
		}
		Map<Integer,ProductBo> productMap = new HashMap<Integer,ProductBo>();
		for(ProductBo productBo:brandBo.getProducts()){
			productMap.put(productBo.getId(), productBo);
		}
		for(Integer productId:dto.getProductIds()){
			if(productMap.containsKey(productId)){
				productMap.remove(productId);
			}else {
				ProductBo productBo = productDao.getProductById(productId);
				brandBo.getProducts().add(productBo);
			}
		}
		for(ProductBo productBoToRemove:productMap.values()){
			brandBo.getProducts().remove(productBoToRemove);
		}
		brandBo.setName(dto.getName());
		brandBo.setLastModifiedTstamp(new Timestamp(System.currentTimeMillis()));
		brandBo.setLastModifiedByUserId(dto.getModifiedById());

		brandDAO.saveBrand(brandBo);
	}
	public IBrandDAO getBrandDAO() {
		return brandDAO;
	}
	public void setBrandDAO(IBrandDAO brandDAO) {
		this.brandDAO = brandDAO;
	}

	public IProductDAO getProductDao() {
		return productDao;
	}

	public void setProductDao(IProductDAO productDao) {
		this.productDao = productDao;
	}
}
